package com.yiboshi.rehrs.config;

import cn.hutool.core.lang.Pair;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.domain.entity.SmZhongUser;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.helper.LimitHelper;
import com.yiboshi.rehrs.helper.RedisHelper;
import com.yiboshi.rehrs.param.smurfs.UserInfo;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * spring mvc 配置中心
 *
 * @author LiuYong
 */
@Component
@Order
@Slf4j
public class ConfigurerAdapterInterceptor implements WebMvcConfigurer, HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(ConfigurerAdapterInterceptor.class);


    @Autowired
    @Lazy
    RedisHelper redisHelper;

    @Autowired
    @Lazy
    LimitHelper limitHelper;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestURI = request.getRequestURI();
        boolean swaggerEn =RehrsSystemConfig.getProfile().contains("prod")||
                RehrsSystemConfig.getProfile().contains("ali")
                ;
        if(swaggerEn&&
                (requestURI.endsWith("docs.html"))
        ){
            return false;
        }
        if(swaggerEn&&requestURI.contains("swagger")){
            return false;
        }
        if(swaggerEn&&requestURI.contains("v2/api-docs")){
            return false;
        }
        String trackId = MDC.get(VarConstant.trackKey);
        if(trackId==null){
            trackId = UUID.randomUUID().toString();
            MDC.put(VarConstant.trackKey,trackId);
        }
        request.setAttribute(VarConstant.startTimeKey,System.currentTimeMillis());

        try{
            String sauth = request.getHeader("sauth");
            if(StringUtils.isEmpty(sauth)){
                sauth = request.getHeader("X-Auth");
                if(StringUtils.isNotEmpty(sauth)&&sauth.length()>2){
                    sauth =sauth.substring(2);
                }
            }
            String nauth = request.getHeader("nauth");
            if(StringUtils.isEmpty(nauth)){
                nauth = request.getHeader("X-Sign");
                if(StringUtils.isNotEmpty(nauth)&&nauth.length()>8){
                    nauth =nauth.substring(8);
                }
            }
            boolean b = LimitHelper.checkNAuth(nauth);
            //boolean account = limitHelper.checkSAuth(sauth);
            //ThreadLocalSession.setHeaderAuthValid(b||account!=null);
            ThreadLocalSession.setHeaderAuthValid(true);
            log.info("收到请求,{}:{},nauth:{},nauth valid:{},sauth:{},account:{}",request.getMethod(),requestURI,nauth,b,sauth);
        }catch (Exception e){
            log.info("{}",e.getMessage());
        }
        ThreadLocalSession.setMode(0);
        if(requestURI.contains("/smf/")){
            ThreadLocalSession.setMode(1);
            //蓝精灵请求
            //if(requestURI.contains("further")){
            String authorization = WebUtils.getHeaderValue(request, VarConstant.Authorization);
            if(StrUtils.isNotBlank(authorization)){
;               // String token = JwtUtil.getToken(authorization);
                String key = "authorization-pair:"+authorization;
                Pair<String, String> pair = CacheUtils.getByCache10Hour(key, Pair.class);
                if(pair==null){
                    pair = AesGcmUtil.decryptAccount(authorization);
                    CacheUtils.putByCache10Hour(key,pair);
                }
                if(pair!=null){
                    String token = pair.getKey();
                    SmZhongUser smZhongUser = redisHelper.smLoadSession(token);
                    if(smZhongUser!=null){
                        ThreadLocalSession.setSmUserInfo(smZhongUser);
                        //检查登录没有登录自动登录
                    }
                }
            }
            //MDC.put(VarConstant.Authorization,authorization);
            //}
        }

        return true;
       /* boolean valid  = false;
        try {
            valid = true;
        }finally {
            //用户错误记录日志
            if(!valid){
                MDC.clear();
            }
        }
        return valid;*/
    }


    //视图渲染之后执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        try {

            Long startTime = (Long) httpServletRequest.getAttribute(VarConstant.startTimeKey);
            if (startTime == null) {
                return;
            }
            String requestURI = httpServletRequest.getRequestURI();
            long currentTimeMillis = System.currentTimeMillis();
            long time = currentTimeMillis - startTime;
            log.info("requestURI:{},总耗时:{}ms", requestURI, time);
            if (time > 5000) {
                log.warn("requestURI:{},总耗时:{}ms,超过5s", requestURI, time);
            }
        } finally {
            ThreadLocalSession.clear();
        }


    }

}
